package com.yinhai.uid.config;

import com.yinhai.uid.UidGenerator;
import com.yinhai.uid.impl.CachedUidGenerator;
import com.yinhai.uid.impl.DefaultUidGenerator;
import com.yinhai.uid.worker.RedisWorkerIdAssigner;
import com.yinhai.uid.worker.WorkerIdAssigner;
import com.yinhai.uid.worker.ZookeeperWorkerIdAssigner;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author taojie
 * @Date: 2018/12/27 09:27
 * @Description:
 */

@Configuration
public class UidGeneratorConfiguration {

	@Bean(name = "workerIdAssigner")
	@ConditionalOnProperty(name="uid.implementation",havingValue = "redis")
	public WorkerIdAssigner redisWorkerIdAssigner(){
		WorkerIdAssigner workerIdAssigner = new RedisWorkerIdAssigner();
		return workerIdAssigner;
	}

	@Bean(name = "workerIdAssigner")
	@ConditionalOnProperty(name="uid.implementation",havingValue = "zookeeper")
	@ConfigurationProperties("uid.worker-id-assigner.zookeeper")
	public WorkerIdAssigner zookeeperWorkerIdAssigner(){
		WorkerIdAssigner workerIdAssigner = new ZookeeperWorkerIdAssigner();
		return workerIdAssigner;
	}

	@Bean(name = "uidGenerator")
	@ConditionalOnProperty(name="uid.implementation",havingValue = "zookeeper")
	@ConfigurationProperties("uid.default-generator")
	public UidGenerator defaultUidGenerator(@Qualifier("workerIdAssigner") WorkerIdAssigner workerIdAssigner){
		DefaultUidGenerator defaultUidGenerator = new DefaultUidGenerator();
		defaultUidGenerator.setWorkerIdAssigner(workerIdAssigner);
		return defaultUidGenerator;
	}

	@Bean(name = "uidGenerator")
	@ConditionalOnProperty(name="uid.implementation",havingValue = "zookeeperCache")
	@ConfigurationProperties("uid.cache-generator")
	public UidGenerator cachedUidGenerator(@Qualifier("workerIdAssigner") WorkerIdAssigner workerIdAssigner){
		CachedUidGenerator cachedUidGenerator = new CachedUidGenerator();
		cachedUidGenerator.setWorkerIdAssigner(workerIdAssigner);
		return cachedUidGenerator;
	}

}
